// 对于axios 封装
import axios from "axios";
import { ElMessage } from "element-plus";
import useUserStore from "@/store/modules/user.ts";
const request = axios.create({
  //baseURL: 'http://139.198.34.216:8201/',
  // 基础路径
  baseURL: "/api",
  timeout: 5000,
});
// 请求拦截器
request.interceptors.request.use(
  (config) => {
    let userStore = useUserStore();
    if (userStore.userInfo.token) {
      config.headers["token"] = userStore.userInfo.token;
    }
    return config;
  },
  (error) => {
    console.log("请求异常", error);
  },
);
// 响应拦截器
request.interceptors.response.use(
  (res) => {
    return res.data;
  },
  (error) => {
    let status = error.response.status;
    switch (status) {
      case 401:
        ElMessage.error("登录失效，请重新登录");
        break;
      case 403:
        ElMessage.error("没有权限");
        break;
      case 404:
        ElMessage.error("请求的资源不存在");
        break;
      case 500 | 501 | 502 | 503 | 504:
        ElMessage.error("服务器错误");
        break;
    }
    return Promise.reject(new Error(error.message));
  },
);

export default request;
